import os
import json
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from django.urls import reverse
from django.views import View
from django.conf import settings
from web import models
from web.models import Book
from web.form import BookForm

# Create your views here.

class Login(View):
    pass

class Register(View):
    pass

class BookList(View):
    def get(self, request):
        book_obj_list = models.Book.objects.all()

        return render(request, "web2/bookList.html", {"book_obj_list": book_obj_list})

class BookChange(View):
    def get(self, request, id=None):
        book_obj = models.Book.objects.filter(pk=id).first()
        form_obj = BookForm(instance=book_obj)
        content = "编辑书籍" if id else "添加书籍"

        return render(request, "web2/bookChange.html", {"form_obj": form_obj, "content": content})

    def post(self, request, id=None):
        print(request.POST)
        print(id)
        book_obj = models.Book.objects.filter(pk=id).first()
        form_obj = BookForm(request.POST, instance=book_obj)
        if form_obj.is_valid():
            form_obj.save()
            res_dict = {'status': True, 'url': reverse('web2:bookList')}
            # res_dict_json = jsocn.dumps(res_dict)
            # print('res_dict_json', res_dict_json)
            # return HttpResponse(res_dict_json, content_type="application/json")

            return JsonResponse(res_dict, json_dumps_params={"ensure_ascii":False}, safe=False)
        else:
            res_dict = {"status": False, "errors": "错了"}
            return JsonResponse(res_dict, json_dumps_params={"ensure_ascii":False}, safe=False)

class BookDelete(View):
    def get(self, request, id=None):
        models.Book.objects.filter(pk=id).delete()

        return redirect(reverse("web2:bookList"))

# ajax实现文件上传
class AjaxUpload(View):
    def get(self, request):
        return render(request, "web2/ajaxUpload.html")

    def post(self, request):
        username = request.POST.get("username")
        password = request.POST.get("password")
        file_obj = request.FILES.get("file")
        file_name = file_obj.name
        print(username, password, file_obj, file_name)

        os.makedirs("%s/files/%s" % (settings.BASE_DIR, username))

        path = os.path.join(settings.BASE_DIR, "files", username, file_name)

        with open(path, "wb") as f:
            for chunk in file_obj.chunks():
                f.write(chunk)

        return HttpResponse("ok")




